import * as THREE from 'three'
import { gsap } from 'gsap'
import vertexShader from './vertexShader.glsl';
import fragmentShader from './fragmentShader.glsl';
import atmoVertexShader from './atmoVertexShader.glsl';
import atmoFragmentShader from './atmoFragmentShader.glsl';

export default function useEarth(innerWidth: number, innerHeight: number) {
    const group = new THREE.Group();
    const texLoader = new THREE.TextureLoader()
    const texture = texLoader.load('./source/textures/earth.jpg')
    // texture.encoding = THREE.sRGBEncoding
    const sphere = new THREE.Mesh(
        new THREE.SphereGeometry(5, 50, 50),
        new THREE.ShaderMaterial({
            // transparent: true,
            uniforms: {
                globeTexture: {
                    value: texture
                }
            },
            vertexShader,
            fragmentShader
        })
    )
    group.add(sphere);

    const atmosphere = new THREE.Mesh(
        new THREE.SphereGeometry(5, 50, 50),
        new THREE.ShaderMaterial({
            side: THREE.BackSide,
            blending: THREE.AdditiveBlending,
            vertexShader: atmoVertexShader,
            fragmentShader: atmoFragmentShader
        })
    )
    atmosphere.scale.set(1.2, 1.2, 1.2)
    group.add(atmosphere);

    const mouse = {
        x: undefined,
        y: undefined
    }
    function animate() {
        window.requestAnimationFrame(animate);
        gsap.to(group.rotation, {
            x: -mouse.y * 0.3,
            y: mouse.x * 0.5,
            duration: 2
        });
    }
    gsap.timeline({
        repeat: -1,
        yoyo: true,
        repeatDelay: 0,
        onUpdate() {
            sphere.rotation.y += 0.002;
        }
    })
    animate();
    window.addEventListener("mousemove", (event) => {
        mouse.x = (event.clientX / innerWidth) * 2 - 1
        mouse.y = -(event.clientY / innerHeight) * 2 + 1
    })
    // gsap.timeline();

    return { earth: group };
}
